//
//  MainTabBar.swift
//  SinaWeibo
//
//  Created by apple on 15/11/8.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

class MainTabBar: UITabBar {
    
    //默认的构造方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setUPUI()
    }
    
    
    //如果重写了init :frame 这个方法 系统会默认为这个控件是通过代码创建的
    required init?(coder aDecoder: NSCoder) {
        //只有一个默认的报错的语句 如果有调用者通过XIB 或者 SB创建了该对象 系统就会崩溃
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
    }
    
    //添加撰写按钮
    private func setUPUI() {
        
        addSubview(editBtn)
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        //遍历子控件 进行布局
        let w = self.bounds.width / 5
        
        let h = self.bounds.height
        
        let rect = CGRect(x: 0, y: 0, width: w, height: h)
        
        var index:CGFloat = 0
        
        for subview in subviews {
            
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                subview.frame = CGRectOffset(rect, index * w, 0)
//                
//                if index == 1 {
//                    
//                    index++
//                }
//                index++
            //三目
                index+=index == 1 ? 2 : 1
            }
            
            //设置撰写按钮的布局
            editBtn.frame = CGRectOffset(rect, w * 2, -10)
            
            bringSubviewToFront(editBtn)
        }
    }
    
    //懒加载撰写按钮
    lazy var editBtn:UIButton = {
        
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState:UIControlState.Normal)
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState:UIControlState.Highlighted)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.sizeToFit()
        
        return btn;
        }()
}


